package huaweiod.first;

import java.util.*;

/**
 * 华为OD机试真题 Java 实现【字符串重新排列】【2022.11 Q4新题】
 *
 * @author yujiafan
 * @version 1.0.0
 * @create 2023-06-21
 */
public class A_2023_03_StringReSort {

    public static String reSort(String str) {
        if (str == null || str.length() == 0) {
            return str;
        }
        String[] splitStr = str.split(" ");
        HashMap<String, Integer> strMap = new HashMap<>();
        // 逆序调整
        for (String s : splitStr) {
            char[] chars = s.toCharArray();
            Arrays.sort(chars);
            String key = String.valueOf(chars);
            if (strMap.containsKey(key)) {
                strMap.put(key, strMap.get(key) + 1);
            } else {
                strMap.put(key, 1);
            }
        }
        // 转化为List进行排序
        ArrayList<Map.Entry<String, Integer>> list = new ArrayList<>(strMap.entrySet());
        list.sort(new Comparator<Map.Entry<String, Integer>>() {
            @Override
            public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                if (o1.getValue() > o2.getValue()) {
                    return -1;
                } else if (o1.getValue().equals(o2.getValue())) {
                    if (o1.getKey().length() < o2.getKey().length()) {
                        return -1;
                    } else if (o1.getKey().length() == o2.getKey().length()) {
                        return o1.getKey().compareTo(o2.getKey());
                    } else {
                        return 1;
                    }
                } else {
                    return 1;
                }
            }
        });
        String res = "";
        for (Map.Entry<String, Integer> entry : list) {
            for (int i = 0; i < entry.getValue(); i++) {
                res = res + entry.getKey() + " ";
            }
        }
        return res.substring(0, res.length() - 1);
    }

    public static void main(String[] args) {
        String s1 = "This is an apple";
        System.out.println(s1);
        System.out.println(reSort(s1));
        // an is This aelpp
        System.out.println("an is This aelpp".equals(reSort(s1)));

        String s2 = "My sister is in the house not in the yard";
        System.out.println(s2);
        // in in eht eht My is not adry ehosu eirsst
        System.out.println(reSort(s2));
    }
}
